package com.alkaid.user.utils;

import com.alkaid.commons.msg.MsgDefinition;
import com.alkaid.commons.ex.CacheException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author Kylin
 */
@Component
public class RedisUtils {
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public boolean save2Redis(String key, Object value, long expireTime) throws CacheException {
        System.out.println(redisTemplate);
        if (expireTime == 0) {
            // 如果是0，则代表-1
            expireTime = -1;
        } else if (expireTime < -1) {
            // 如果小于-1，代表的数绝对值
            expireTime = Math.abs(expireTime);
        }
        try {
            redisTemplate.opsForValue().set(key, value);
            if (expireTime > 0) {
                // 设置有效期，时间单位是s
                redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new CacheException(MsgDefinition.CACHE_FAILED);
        }
        return true;
    }

    public Object getFromRedis(String key) {
        try {
            return redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            return null;
        }
    }

    public boolean deleteKey(String key) throws Exception {
        Boolean result = redisTemplate.delete(key);
        return result != null && result;
    }
}
